struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};




class Solution {
    int curSum = 0;
public:
    TreeNode* convertBST(TreeNode* root) {
        dfs(root);
        return root;

    }

    void dfs(TreeNode* node) {
        if (!node) return;
        if (node->right) dfs(node->right);
        curSum += node->val;
        node->val = curSum;
        dfs(node->left);
        return;
    }
};